import React, { useState } from 'react';
import { Card, Button, Select, message, Spin, Result } from 'antd';
import { CopyOutlined, ReloadOutlined } from '@ant-design/icons';
import { pdfApi } from '../../services/api';
import { handleApiError } from '../../utils/error';
import FileUploader from '../../components/common/FileUploader';

const { Option } = Select;

const OCRScanner: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const [result, setResult] = useState('');
  const [lang, setLang] = useState('chi_sim+eng');
  const [error, setError] = useState<string | null>(null);

  const handleUpload = async (files: File[]) => {
    const file = files[0];
    setError(null);
    try {
      setLoading(true);
      const text = await pdfApi.performOCR(file, lang);
      setResult(text);
      message.success('识别成功！');
    } catch (err) {
      handleApiError(err);
      setError('识别失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(result);
      message.success('已复制到剪贴板！');
    } catch {
      message.error('复制失败，请手动复制');
    }
  };

  const handleReset = () => {
    setResult('');
    setError(null);
  };

  return (
    <Card
      title="OCR文字识别"
      extra={
        <Select
          value={lang}
          onChange={setLang}
          style={{ width: 150 }}
          disabled={loading}
        >
          <Option value="chi_sim+eng">中文+英文</Option>
          <Option value="chi_sim">仅中文</Option>
          <Option value="eng">仅英文</Option>
        </Select>
      }
    >
      {error ? (
        <Result
          status="error"
          title={error}
          extra={
            <Button type="primary" onClick={handleReset}>
              重试
            </Button>
          }
        />
      ) : (
        <>
          <FileUploader
            accept=".pdf,.png,.jpg,.jpeg"
            onUpload={handleUpload}
            loading={loading}
            description="支持PDF和常见图片格式（JPG、PNG等）"
          />

          {loading && (
            <div style={{ textAlign: 'center', margin: '24px 0' }}>
              <Spin tip="正在识别中..." />
            </div>
          )}

          {result && !loading && (
            <Card
              title="识别结果"
              style={{ marginTop: 16 }}
              extra={
                <Button.Group>
                  <Button
                    type="primary"
                    icon={<CopyOutlined />}
                    onClick={handleCopy}
                  >
                    复制文本
                  </Button>
                  <Button
                    icon={<ReloadOutlined />}
                    onClick={handleReset}
                  >
                    重新识别
                  </Button>
                </Button.Group>
              }
            >
              <pre style={{ 
                whiteSpace: 'pre-wrap', 
                wordWrap: 'break-word',
                maxHeight: '400px',
                overflow: 'auto',
                padding: '16px',
                backgroundColor: '#f5f5f5',
                borderRadius: '4px'
              }}>
                {result}
              </pre>
            </Card>
          )}
        </>
      )}
    </Card>
  );
};

export default OCRScanner; 